using System;
using System.Globalization;
using System.Linq;
using Gtk;
using System.Collections.Generic;
using NLog;
using NetworkCommsDotNet;

namespace JiveMessengerLinux
{
    public partial class EmoticonWindow : Gtk.Window
    {
        public event EventHandler<EmoticonClickedEventArgs> EmoticonClickedEvent;
        public event EventHandler<EventArgs> AddEmoticonEvent;
        public EmoticonWindow()
            : base(Gtk.WindowType.Toplevel)
        {
            this.Build();
            Gtk.ListStore defaultEmoticonStore = CreateDefaultModel();
            this.UpdateDefaultEmoticonModel(defaultEmoticonStore);
            this.iconviewDefaultEmoticons.Model = defaultEmoticonStore;
            this.iconviewDefaultEmoticons.ShowAll();
            this.iconviewDefaultEmoticons.PixbufColumn = 1;
            this.iconviewDefaultEmoticons.CheckResize();
            this.iconviewDefaultEmoticons.SelectionChanged += new EventHandler(this.iconviewDefaultEmoticons_SelectionChanged);

            Gtk.ListStore customEmoticonStore = CreateCustomModel();
            this.UpdateCustomEmoticonModel(customEmoticonStore);
            this.iconviewCustomEmoticons.Model = customEmoticonStore;
            this.iconviewCustomEmoticons.ShowAll();
            this.iconviewCustomEmoticons.PixbufColumn = 1;
            this.iconviewCustomEmoticons.CheckResize();
            this.iconviewCustomEmoticons.ResizeChildren();
            this.iconviewCustomEmoticons.SelectionChanged += new EventHandler(iconviewCustomEmoticons_SelectionChanged);
            Gtk.LinkButton linkBn = new LinkButton("", "Create");

            linkBn.Visible = true;
            //linkBn.ShowAll();
            linkBn.Clicked += new EventHandler((s, e) =>
                {
                    AddEmoticonEvent(this, null);
                });
            this.hbox1.PackEnd(linkBn, false, false, 0);


        }

        public void ClearSelection()
        {
            iconviewCustomEmoticons.SelectedItems.ToList().Clear();
            iconviewDefaultEmoticons.SelectedItems.ToList().Clear();
        }

        private void iconviewCustomEmoticons_SelectionChanged(object sender, EventArgs e)
        {
            if (this.iconviewCustomEmoticons.SelectedItems.Length == 0)
                return;
            TreeIter iter;
            this.iconviewCustomEmoticons.Model.GetIter(out iter, this.iconviewCustomEmoticons.SelectedItems[0]);
           // string[] path = (string[])this.iconviewDefaultEmoticons.Model.GetValue(iter, 0);
            string s = this.iconviewCustomEmoticons.Model.GetValue(iter, 0).ToString();// path[0];

            EmoticonClickedEvent(this, new EmoticonClickedEventArgs(s));
        }

        private void iconviewDefaultEmoticons_SelectionChanged(object sender, EventArgs e)
        {
            if (this.iconviewDefaultEmoticons.SelectedItems.Length == 0)
                return;
            TreeIter iter;
            this.iconviewDefaultEmoticons.Model.GetIter(out iter, this.iconviewDefaultEmoticons.SelectedItems[0]);
            string[] path = (string[])this.iconviewDefaultEmoticons.Model.GetValue(iter, 0);
            string s = path[0];

            EmoticonClickedEvent(this, new EmoticonClickedEventArgs(s));
        }



        private Gtk.ListStore CreateDefaultModel()
        {
            ListStore store = new ListStore(typeof(string[]), typeof(Gdk.Pixbuf), typeof(bool));
            store.DefaultSortFunc = SortFunc;
            store.SetSortColumnId(2, SortType.Ascending);
            
            return store;
        }
        private Gtk.ListStore CreateCustomModel()
        {
            ListStore store = new ListStore(typeof(string), typeof(Gdk.Pixbuf), typeof(bool));
            store.DefaultSortFunc = SortFunc;
            store.SetSortColumnId(2, SortType.Ascending);

            return store;
        }
        int SortFunc(TreeModel model, TreeIter a, TreeIter b)
        {
            // sorts folders before files
            bool a_is_custom = (bool)model.GetValue(a, 2);
            bool b_is_custom = (bool)model.GetValue(b, 2);
            string a_name = (string)model.GetValue(a, 0);
            string b_name = (string)model.GetValue(b, 0);

            if (!a_is_custom && b_is_custom)
                return 1;
            else if (a_is_custom && !b_is_custom)
                return -1;
            else
                return String.Compare(a_name, b_name);
        }

        public void UpdateDefaultEmoticonModel(Gtk.ListStore store)
        {
            store.Clear();

            foreach (KeyValuePair<string[], string> kvp in StaticSettings.DefaultEmoticons)
            {
                try
                {
                    Gdk.Pixbuf pix = new Gdk.Pixbuf(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("JiveMessengerLinux.Resources." + kvp.Value));
                    store.AppendValues(kvp.Key, pix, true);
                }
                catch (Exception err)
                {
                    NetworkComms.Logger.ErrorException("Error loading emoticon " + kvp.Value, err);
                }
            }
        }
        public void UpdateCustomEmoticonModel(Gtk.ListStore store)
        {
            store.Clear();
            foreach (KeyValuePair<string, string> kvp in StaticSettings.CustomEmoticons)
            {
                try
                {
                    Gdk.Pixbuf original = new Gdk.Pixbuf(kvp.Value);
                    int width = original.Width;
                    int height = original.Height;
                    if (width >= 50)
                        width = Int32.Parse((width*0.7).ToString(CultureInfo.InvariantCulture));
                    if (height >= 50)
                        height = Int32.Parse((height * 0.7).ToString(CultureInfo.InvariantCulture));


                    store.AppendValues(kvp.Key, new Gdk.Pixbuf(kvp.Value,width,height), false);
                }
                catch (Exception err)
                {
                    NetworkComms.Logger.ErrorException("Error loading emoticon " + kvp.Value, err);
                }

            }
        }
    }
}
